<?php
namespace App\Lib\Pay;

use EasyWeChat\Factory;

class WxPay
{

    public static function pay($openid,$total_fee,$out_trade_no,$body)
    {

        $options = [
            'app_id' => env('WX_APPID'),
            'mch_id' => env('MCH_ID'),
            'key' => env('MCH_KEY'),
            'notify_url' => env('APP_URL').'/api/v1/notify',
        ];

        $payment = Factory::payment($options);
        $jssdk = $payment->jssdk;

        $attributes = [
            'trade_type' => 'JSAPI',              // 支付方式，小程序支付使用JSAPI
            'body' => $body,            // 订单说明
            'out_trade_no' => $out_trade_no,  // 自定义订单号
            'total_fee' => floatval($total_fee) * 100,               // 单位：分
            'openid' => $openid                   // 当前用户的openId
        ];

        $result = $payment->order->unify($attributes);

        if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
            $prepayId = $result['prepay_id'];
            $config = $jssdk->sdkConfig($prepayId);
            return $config;
        }

        if ($result['return_code'] == 'FAIL' && array_key_exists('return_msg', $result)) {
            return $result;
        }

        return $result;
    }

}
